<template>
  <PublicPage ref="publiceRef" pageName="帮卖介绍" class="hell-sell-introduce">
    <scroll-view scroll-y class="scroll_view">
      <!-- 警告提示 -->
      <view v-if="infoData.isMyself" class="alert-tips">在主页时，帮卖介绍仅您的帮卖团长可见</view>
      <view class="main-wrap">
        <!-- 社群数据 -->
        <Card headerText="相关数据" :hasEdit="!!infoData.isMyself" @edit="_mySelfEdit">
          <view v-if="helpSellEmpty" class="myself-empty">
            {{infoData.isMyself?'暂未添加展示数据类型～':'团长暂未公开相关数据'}}
          </view>
          <view v-else class="myself-data">
            <view class="u-flex u-flex-wrap">
              <view v-if="hasShow(infoData.headCount)" class="flex-item">
                <view class="num">{{playvolumeFn(infoData.headCount)}}</view>
                <view class="text">帮卖团长(人)</view>
              </view>
              <view v-if="hasShow(infoData.memberCount)" class="flex-item">
                <view class="num">{{playvolumeFn(infoData.memberCount)}}</view>
                <view class="text">成员(人)</view>
              </view>
              <view v-if="hasShow(infoData.giveCommission)" class="flex-item">
                <view class="num">{{playvolumeFn(infoData.giveCommission)}}</view>
                <view class="text">已发佣金(元)</view>
              </view>
              <view v-if="hasShow(infoData.saleCount)" class="flex-item">
                <view class="num">{{playvolumeFn(infoData.saleCount)}}</view>
                <view class="text">累计销量(件)</view>
              </view>
              <view v-if="hasShow(infoData.saleAmount)" class="flex-item">
                <view class="num">{{playvolumeFn(infoData.saleAmount)}}</view>
                <view class="text">销售总额(元)</view>
              </view>
            </view>
          </view>
        </Card>
        <!-- 帮卖介绍 -->
        <Card :headerText="introduceText" :hasEdit="!!infoData.isMyself&&infoData.introduceImg" @edit="_goRichEdit">
          <view v-if="infoData.introduceImg" class="help-data">
            <rich-text :nodes="infoData.introduceImg" />
          </view>
          <view v-else class="help-empty">
            <!-- 自己 -->
            <template v-if="infoData.isMyself">
              <view class="empty-text">您暂时没有填写帮卖介绍，填写帮卖介绍可吸引更多人来帮卖哦～</view>
              <button class="empty-btn" @click.stop="_goRichEdit">立即填写</button>
            </template>
            <!-- TA人-->
            <view v-else class="myself-empty">团长暂时没有填写帮卖简介～</view>
          </view>
        </Card>
      </view>
      <view v-if="relationType==2||infoData.isMyself" class="fixedBottomBtn" :style="{bottom}">
        <!-- 帮卖介绍--自己--展示分享按钮 -->
        <template v-if="infoData.isMyself">
          <button v-if="(helpSellEmpty&&!infoData.introduceImg)||isTwo<2" class="share-btn" @click="_checkShare">分享</button>
          <button v-else open-type="share" id="shareUser" class="share-btn">分享</button>
        </template>
        <template v-else>
          <!-- 帮卖介绍--团长--去帮卖 -->
          <button v-if="relationType==2" class="share-btn" @click="_goHomePage">去帮卖</button>
        </template>
      </view>
      <u-popup
          v-model="dlMySelf"
          border-radius="24"
          mode="bottom"
          safe-area-inset-bottom
          @maskClick="dlMySelf=false"
      >
        <view class="popup-main">
          <view class="popup-header">
            <view class="main-text">选择您要展示的数据</view>
            <view class="sub-text">社群数据截止到前一日、每日零点更新</view>
          </view>
          <view class="popup-list">
            <view class="item" @click.stop="_changeCommunity('isShowHeadCount', communityData.isShowHeadCount)">
              <view class="item_l">
                <text class="l-tip">帮卖团长</text>
                <text class="l-num">{{playvolumeFn(communityData.headCount)}}人</text>
              </view>
              <view>
                <i class="iconfont"
                   :class="{
                  'icon-checkbox': !communityData.isShowHeadCount,
                  'icon-checkbox_fill': communityData.isShowHeadCount
                }"
                />
              </view>
            </view>
            <view class="item" @click.stop="_changeCommunity('isShowMemberCount', communityData.isShowMemberCount)">
              <view class="item_l">
                <text class="l-tip">成员</text>
                <text class="l-num">{{playvolumeFn(communityData.memberCount)}}人</text>
              </view>
              <view>
                <i class="iconfont"
                   :class="{
                  'icon-checkbox': !communityData.isShowMemberCount,
                  'icon-checkbox_fill': communityData.isShowMemberCount
                }"
                />
              </view>
            </view>
            <view class="item" @click.stop="_changeCommunity('isShowGiveCommission', communityData.isShowGiveCommission)">
              <view class="item_l">
                <text class="l-tip">已发佣金</text>
                <text class="l-num">{{playvolumeFn(communityData.giveCommission)}}元</text>
              </view>
              <view>
                <i class="iconfont"
                   :class="{
                  'icon-checkbox': !communityData.isShowGiveCommission,
                  'icon-checkbox_fill': communityData.isShowGiveCommission
                }"
                />
              </view>
            </view>
            <view class="item" @click.stop="_changeCommunity('isShowSaleCount', communityData.isShowSaleCount)">
              <view class="item_l">
                <text class="l-tip">累计销量</text>
                <text class="l-num">{{playvolumeFn(communityData.saleCount)}}件</text>
              </view>
              <view>
                <i class="iconfont"
                   :class="{
                  'icon-checkbox': !communityData.isShowSaleCount,
                  'icon-checkbox_fill': communityData.isShowSaleCount
                }"
                />
              </view>
            </view>
            <view class="item" @click.stop="_changeCommunity('isShowSaleAmount', communityData.isShowSaleAmount)">
              <view class="item_l">
                <text class="l-tip">销售总额</text>
                <text class="l-num">{{playvolumeFn(communityData.saleAmount)}}元</text>
              </view>
              <view>
                <i class="iconfont"
                   :class="{
                  'icon-checkbox': !communityData.isShowSaleAmount,
                  'icon-checkbox_fill': communityData.isShowSaleAmount
                }"
                />
              </view>
            </view>
          </view>
          <view class="popup-btn">
            <button class="button" @click="_onSubmitCommunity">选好了</button>
          </view>
        </view>
      </u-popup>
      <u-modal
          v-model="dlEmpty"
          :show-title="false"
          confirm-text="好的"
          confirm-color="#E44435"
          content="你还未填写内容，填写后再分享哦～"
      />
      <!-- 申请帮卖弹框 -->
      <ApplyForHelpSelling
          v-if="dlHelpSell"
          :show="dlHelpSell"
          :othersInfoData="otherData"
          :getRelationType="relationType"
          @cancelFn="()=>dlHelpSell=false"
      />
      <!-- canvas绘制分享卡片背景图 -->
      <InviteToHelpSellShare ref="helpSellRef" @shareSuccess="_drawHSSuccess" />
    </scroll-view>
  </PublicPage>
</template>

<script>
import PublicPage from '@/components/publicPage/index.vue'
import Card from './components/card.vue'
import ApplyForHelpSelling from '../components/applyForHelpSelling.vue'
import InviteToHelpSellShare from '@/components/shareImage/inviteToHelpSellShare.vue'

import helpSellApi from '@/api/helpSellGroups.js'
import ShareApi from '@/api/share.js'
import UserApi from '@/api/user.js'
import Util from '@/api/util.js'

const helpSellNumKeys = ['headCount', 'memberCount', 'giveCommission', 'saleCount', 'saleAmount'] // 该数组顺序不能调整--涉及到分享卡片时全选要按照顺序显示
const helpSellText = {
  headCount: '帮卖团长',
  memberCount: '成员',
  giveCommission: '已发佣金',
  saleCount: '累计销量',
  saleAmount: '销售总额'
}
const helpSellBoolKeys = ['isShowMemberCount', 'isShowGiveCommission', 'isShowHeadCount', 'isShowSaleAmount', 'isShowSaleCount']

export default {
  name: 'helpSellIntroduce',
  components: {
    PublicPage,
    Card,
    ApplyForHelpSelling,
    InviteToHelpSellShare
  },
  data() {
    return {
      routeData: {}, // url参数
      shareObject: {}, // 分享对象--用户分享卡片出去的
      shareData: {}, // 分享对象数据
      dlMySelf: false, // 自己的社群数据编辑弹出框变量
      dlEmpty: false, // 分享时判断内容是否为空弹出框变量
      helpSellEmpty: true, // 社群数据的空状态
      dlHelpSell: false, // 申请帮卖弹出变量
      relationType: 0, // 绑定关系的状态-->0:没有关系, 1:审核中, 2:通过, 3:拒绝
      infoData: {}, // 帮卖社群数据展示对象
      communityData: {}, // 帮卖社群数据编辑对象
      // dataText: '相关数据', // 社群数据的文案
      introduceText: '帮卖介绍', // 帮卖介绍文案
      otherData: {}, // TA人主页详情对象
      isTwo: 0, // 分享背景时累计数字--为2才能分享
      canvasObj: {
        fansText: '',
        watchText: '',
        fansMun: 0,
        watchMun: 0,
        highQualityMun: 0,
        highQualityText: ''
      }, // 绘制海报时的数据对象
    }
  },
  async onLoad(option) {
    this.routeData = option
    // 校验是否登录
    await this.isLoSignInFn(option)
    this.getData()
    // 禁用菜单的分享按钮
    wx.hideShareMenu({
      menus: ["shareAppMessage"]
    })
  },
  onShow() {
    this._getRichData()
    if (this.getIsRefreshType()) {
      this.setIsRefreshType(false)
      this.getData()
    }
  },
  onShareAppMessage(res) {
    // shareUser --> id
    const _shareObj = {
      title: '欢迎查看我的帮卖介绍，优质货源，放心帮卖！',
      imageUrl: this.shareObject.url,
      path: '/pagesB/personalCenter/homePage'
    }
    if (res.from === 'button') {
      if (res.target.id === 'shareUser') {
        // 兼容url链接可能不存在accountId，获取accountId为字符串undefined
        const { accountId } = this.routeData
        if (accountId && accountId !== 'undefined') {
          _shareObj.path = `/pagesB/helpSellIntroduce/index?accountId=${accountId}&shareType=true&applyForHelp=true&idCode=${this.$store.state.userInfo.idCode}`
        } else {
          _shareObj.path = `/pagesB/helpSellIntroduce/index?accountId=${this.$store.state.userInfo.accountId}&shareType=true&shareType=true&applyForHelp=true&idCode=${this.$store.state.userInfo.idCode}`
        }
      }
    }
    console.log(JSON.parse(JSON.stringify({_shareObj})), '分享参数打印')
    return _shareObj
  },
  methods: {
    // 获取帮卖社群数据展示
    getData() {
      const { accountId } = this.routeData
      const params = {}
      if (accountId && accountId !== 'undefined') {
        params.accountId = accountId
      }
      helpSellApi.getHelpSellIntroduce(params).then(res => {
        this.infoData = res.data
        // 是自己的，调用分享数据接口
        if (this.infoData.isMyself){
          this.getShareData()
        } else {
          // 非自己时需要查询绑定关系
          this.getOtherData()
        }
        // 标识社群数据是否全部不展示--即空状态
        for (let i = 0, length = helpSellNumKeys.length; i < length; i++) {
          const key = helpSellNumKeys[i]
          if (this.infoData[key] !== null && this.infoData[key] !== undefined) {
            this.helpSellEmpty = false
            break
          } else {
            this.helpSellEmpty = true
          }
        }
        // console.log(res, '获取帮卖社群数据展示')
      })
    },
    // 获取帮卖社群数据编辑信息
    getCommounity() {
      helpSellApi.getHelpSellCommunity().then(res => {
        this.communityData = res.data
        // console.log(res, '获取帮卖社群数据编辑信息')
      })
    },
    // 自己的社群数据编辑
    _mySelfEdit() {
      if (this.infoData.isMyself) {
        this.dlMySelf = true
        this.getCommounity()
      }
    },
    // 切换帮卖社群数据展示
    _changeCommunity(key, val) {
      this.communityData[key] = val ? 0 : 1
      // console.log(this.communityData, '切换帮卖社群数据展示')
    },
    // 确认帮卖社群数据展示
    _onSubmitCommunity() {
      let sum = 0 // 用于累计多少个选中的标识
      const params = {}
      // 过滤提交后端需要的字段
      for (let i = 0, length = helpSellBoolKeys.length; i < length; i++) {
        const key = helpSellBoolKeys[i]
        const val = this.communityData[key]
        params[key] = val
        if (val) ++sum
      }
      if (sum < 2) {
        return wx.showToast({
          icon: 'none',
          title: `展示的数据最少为2个`,
          duration: 1500
        })
      }
      helpSellApi.updateCommunityInfo(params).then(res => {
        if (res.code === 200) {
          this.getData()
          this.dlMySelf = false
        }
      })
    },
    // 获取分享卡片、分享朋友圈用户数据信息
    getShareData() {
      ShareApi.getShareInfo({}).then(res => {
        this.shareData = res.data
        this._filterHasVal()
        // 累计有两项才绘制海报
        if (this.isTwo >= 2) this.drawInvite(this.canvasObj)
      })
    },
    // 判断社群数据展示是否有两项+将要绘制的数据
    _filterHasVal() {
      // 筛选出前两项有值的进行绘制
      this.isTwo = 0
      for (let i = 0, length = helpSellNumKeys.length; i < length; i++) {
        if (this.isTwo >= 3) break

        const key = helpSellNumKeys[i]
        const val = this.infoData[key]

        if (val !== null && val !== undefined) {
          ++this.isTwo
          if (this.isTwo === 1) {
            this.canvasObj.fansText = helpSellText[key]
            this.canvasObj.fansMun = val
            this.canvasObj.highQualityText = ''
          } else if (this.isTwo === 2) {
            this.canvasObj.watchText = helpSellText[key]
            this.canvasObj.watchMun = val
            this.canvasObj.highQualityText = ''
          } else if (this.isTwo === 3) {
            this.canvasObj.highQualityText = helpSellText[key]
            this.canvasObj.highQualityMun = val
          }
        }
      }
    },
    // 分享朋友卡片背景绘制
    drawInvite({ fansText, watchText, fansMun, watchMun, highQualityText, highQualityMun }) {
      const canvasData = {
        type: 2,
        fansText: fansText,
        highQualityText: highQualityText,
        watchText: watchText,
        btnText: '立即查看',
        isLoadType: true,
      }
      const { isMyself } = this.infoData
      if (isMyself) {
        const { communityLogo, communityName } = this.shareData
        //, saleCount, memberCount
        const { introduce } = this.infoData
        canvasData.userAvatar = communityLogo || defaultAvatar // 团长头像
        canvasData.userNickname = communityName || '速速团'
        canvasData.title = introduce || '这有超多好货，欢迎入团帮卖！'
        canvasData.fansMun = Util.playvolume(fansMun || 0)
        canvasData.highQualityMun = Util.playvolume(highQualityMun || 0)
        canvasData.watchMun = Util.playvolume(watchMun || 0)
      }
      this.$refs.helpSellRef.shareFrends(canvasData)
    },
    // 分享卡片背景绘制成功回调
    _drawHSSuccess(res) {
      if (res.code == 200) {
        this.shareObject.url = res.url
      }
    },
    // 查询是否绑定关系
    getRelation(idCode) {
      UserApi.getRelation({ idCode }).then(res => {
        this.relationType = res.data.relation
        if (this.relationType != 2) {
          this.dlHelpSell = true
        }
      })
    },
    // 获取TA人主页详情--用于非自己进入时显示社群昵称、申请帮卖
    getOtherData() {
      const params = {}
      // 兼容分享出去的accountId可能为undefined
      const { accountId } = this.routeData
      // accountId是从融云IM获取的，在链接不到融云的情况下，accountId为undefined
      if (accountId && accountId !== 'undefined') {
        params.accountId = accountId
      }
      UserApi.getOthersInfo(params).then(res => {
        this.otherData = res.data
        this.getRelation(res.data.idCode || this.routeData.idCode)
        // this.dataText = `${this.otherData.communityName}的社群数据`
        this.introduceText = `${this.otherData.communityName}的简介`
      })
    },
    // 跳转到TA人社群主页
    _goHomePage() {
      // 解决页面堆叠问题
      const routePages = getCurrentPages()
      if (routePages.length > 1) {
        const routeObj = routePages[routePages.length - 2]
        // 解决页面堆叠问题
        if (routeObj.route === 'pagesB/personalCenter/homePage') {
          this.navigateBack({ delta: 1 })
        } else {
          this._pushHomePage()
        }
      } else {
        this._pushHomePage()
      }
    },
    // push路由到社群主页
    _pushHomePage() {
      const { accountId } = this.routeData
      // 兼容accountId
      if (accountId && accountId !== 'undefined') {
        this.navigateTo({
          url: `/pagesB/personalCenter/homePage?accountId=${accountId}`
        })
      } else {
        this.navigateTo({
          url: `/pagesB/personalCenter/homePage?accountId=${this.$store.state.userInfo.accountId}`
        })
      }
    },
    // 调整富文本编辑页
    _goRichEdit() {
      this.$store.commit('SET_EDITOR_OBJECT', { html: this.infoData.introduceImg })
      this.navigateTo({
        url: '/pagesB/goods/goodsEditCopy'
      })
    },
    // 获取富文本内容
    _getRichData() {
      const editorObject = this.$store.state.editorObject
      const params = {
        introduceImg: '',
        introduce: '',
        imgUrl: ''
      }
      if (Object.prototype.hasOwnProperty.call(editorObject, 'html')) {
        // 比较html有无变化
        if (this.infoData.introduceImg !== editorObject.html) {
          params.introduceImg = editorObject.html
          if (Object.prototype.hasOwnProperty.call(editorObject, 'image')) {
            params.imgUrl = JSON.stringify(editorObject.image)
          }
          if (Object.prototype.hasOwnProperty.call(editorObject, 'text')) {
            // 匹配回车符
            params.introduce = editorObject.text
          }
          helpSellApi.updateHelpSellIntroduce(params).then(res => {
            if (res.code === 200) {
              // 从社群主页过来--数据更新需要社群主页也需要更新
              const isFromHomePage = this.routeData.from && this.routeData.from === 'homePage'
              if (isFromHomePage) this.setIsRefreshType(true)
              // 从社群主页过来--数据更新需要社群主页也需要更新

              for (const key in params) {
                this.infoData[key] = params[key]
              }
              // 请求成功之后需要重新绘制分享卡片背景图片
              this.drawInvite(this.canvasObj)
              this.$store.commit('SET_EDITOR_OBJECT', {})
            }
          })
          // console.log(this.$store.state.editorObject, '富文本')
        }
      }
    },
    // 格式化数字格式
    playvolumeFn(num) {
      return Util.playvolume(num, '万', false)
    },
    // 社群数据--是否展示在页面
    hasShow(num) {
      // 为null不展示
      if (num === null || num === undefined) {
        return false
      }
      return true
    },
    // 检测是否可以分享
    _checkShare() {
      if (this.helpSellEmpty) {
        this.dlEmpty = true
      } else if (this.isTwo < 2) {
        wx.showToast({
          icon: 'none',
          title: `展示的数据最少为2个`,
          duration: 1500
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.hell-sell-introduce {
  width: 100%;
  .scroll_view {
    height: 100%;
  }
  .alert-tips {
    width: 100%;
    padding: 20rpx 32rpx;
    line-height: 40rpx;
    font-size: 28rpx;
    color: #ED6A0C;
    background-color: #FFFBE8;
  }
  .main-wrap {
    margin-top: 24rpx;
    padding: 0 32rpx 132rpx;
    background-color: #F7F8FA;
  }
  .myself-empty {
    padding: 24rpx 32rpx;
    font-size: 24rpx;
    line-height: 160rpx;
    text-align: center;
    color: $n6Color;
  }
  .myself-data {
    width: 100%;
    .flex-item {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 33.3333%;
      height: 160rpx;
      text-align: center;
    }
    .num {
      margin-bottom: 8rpx;
      line-height: 48rpx;
      font-size: 36rpx;
      font-weight: 500;
      color: $n8Color;
    }
    .text {
      line-height: 32rpx;
      font-size: 24rpx;
      color: $n6Color;
    }
  }
  .help-empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 24rpx 32rpx;
    .empty-text {
      margin-bottom: 40rpx;
      font-size: 28rpx;
      line-height: 40rpx;
      color: $n6Color;
    }
    .empty-btn {
      width: 176rpx;
      height: 64rpx;
      font-size: 28rpx;
      line-height: 64rpx;
      border-radius: 32rpx;
      color: #FFFFFF;
      background-color: $themeColor;
    }
  }
  .help-data {
    padding: 24rpx 32rpx;
    word-break: break-all !important;
  }
  .share-btn {
    width: 100%;
    height: 100rpx;
    line-height: 100rpx;
    text-align: center;
    color: #FFFFFF;
    background-color: $themeColor;
  }
  .popup-main {
    padding: 40rpx 32rpx 0;
  }
  .popup-header {
    box-sizing: border-box;
    width: 100%;
    padding-bottom: 40rpx;
    border-bottom: 2rpx solid $n3Color;
    text-align: center;
    .main-text {
      margin-bottom: 16rpx;
      font-size: 32rpx;
      line-height: 44rpx;
      color: $n8Color;
    }
    .sub-text {
      font-size: 28rpx;
      line-height: 40rpx;
      color: $n6Color;
    }
  }
  .popup-list {
    .item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      height: 148rpx;
    }
    .item_l {
      display: flex;
      flex-direction: column;
    }
    .l-tip {
      margin-bottom: 8rpx;
      line-height: 48rpx;
      font-size: 32rpx;
      color: $n8Color;
    }
    .l-num {
      font-size: 28rpx;
      line-height: 40rpx;
      color: $n6Color;
    }
    .icon-checkbox {
      font-size: 40rpx;
      color: $n6Color;
    }
    .icon-checkbox_fill {
      font-size: 40rpx;
      color: $themeColor;
    }
  }
  .popup-btn {
    width: 100%;
    margin: 20rpx 0;
    .button {
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      border-radius: 44rpx;
      font-size: 32rpx;
      text-align: center;
      background: $themeColor;
      color: #ffffff;
    }
  }
}
</style>
